# apps/roles/serializers.py
from rest_framework import serializers
from .models import Role
from apps.menus.serializers import MenuSerializer

class RoleSerializer(serializers.ModelSerializer):
    menu_tree = serializers.SerializerMethodField()

    class Meta:
        model = Role
        fields = ['id', 'name', 'code', 'description', 'menus', 'order', 'is_active', 'menu_tree']

    def get_menu_tree(self, obj):
        # 返回所有菜单树，当前角色已选中的标记 checked
        from apps.menus.models import Menu
        menus = Menu.objects.filter(is_active=True).exclude(menu_type='button')
        def build_tree(parent=None):
            items = []
            for menu in menus:
                if menu.parent == parent:
                    item = {
                        'id': menu.id,
                        'title': menu.title,
                        'name': menu.name,
                        'checked': menu in obj.menus.all(),
                        'children': build_tree(menu)
                    }
                    items.append(item)
            return items
        return build_tree()